#include <mysql/mysql.h>  // mysql头文件

#include <iostream>
using namespace std;
const int len = 100;
int main() {
  // 创建一个句柄之类的对象，后面都用它来操作表
  MYSQL conn;
  int res;
  // 初始化
  mysql_init(&conn);
  // 连接 -- 对象， 本地， 用户名， 密码， 要操作的表的名称， 0， null，
  // client_found_rows
  if (mysql_real_connect(&conn, "localhost", "root", "newPwd", "test", 0, NULL,
                         CLIENT_FOUND_ROWS)) {
    cout << "# connect success" << endl;
    // 循环添加
    while (1) {
      cout << "----------add item-----------" << endl;
      // 插入数据
      char query_code[len];
      {
        char name[len / 2];
        char data[len / 2];
        cout << "$ [input the name]: ";
        cin >> name;
        cout << "$ [input the data]: ";
        cin >> data;
        sprintf(query_code, "insert into test values('%s', '%s')", name, data);
      }
      res = mysql_query(&conn, query_code);
      if (res) {
        cout << "# Error" << endl;
        break;
      } else {
        cout << "# OK" << endl;
        cout << "# succeed to " << query_code << endl;
      }
      // 是否继续添加
      cout << "# continue ? [y/n]: ";
      char ctn = 'y';
      cin >> ctn;
      if (ctn == 'n' || ctn == 'N') break;
    }
    //关闭
    mysql_close(&conn);
  } else {
    cout << "coonect failed" << endl;
  }
  return 0;
}